/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.gateway.server.filter;

import cn.hutool.core.collection.CollUtil;
import com.iwindplus.base.domain.dto.MessageBaseDTO;
import com.iwindplus.base.domain.enums.BaseEnum;
import com.iwindplus.base.domain.enums.BizCodeEnum;
import com.iwindplus.base.domain.enums.OperateTypeEnum;
import com.iwindplus.base.domain.exception.BizException;
import com.iwindplus.base.util.ReactorUtil;
import com.iwindplus.base.util.UrlUtil;
import com.iwindplus.gateway.server.client.MgtClient;
import com.iwindplus.gateway.server.domain.constant.GatewayConstant.FilterConstant;
import com.iwindplus.gateway.server.domain.constant.GatewayConstant.ServerWebExchangeContextConstant;
import com.iwindplus.gateway.server.domain.property.GatewayProperty;
import com.iwindplus.mgt.domain.dto.system.ApiWhiteListChangeDTO;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

/**
 * API白名单过滤器.
 *
 * @author zengdegui
 * @since 2020/4/15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApiWhiteListFilter implements Ordered, GlobalFilter, ApplicationRunner {

    private final GatewayProperty property;
    private final MgtClient mgtClient;
    private final AtomicReference<Set<String>> snapshot = new AtomicReference<>(Set.of());
    private static final List<String> DEFAULT_IGNORED_APIS = List.of(
        "/v2/api-docs",
        "/v3/api-docs",
        "/oauth2/token",
        "/oauth2/authorize",
        "/oauth2/introspect",
        "/oauth2/revoke",
        "/oauth2/jwks",
        "/oauth2/consent"
    );

    @Override
    public int getOrder() {
        return FilterConstant.FILTER_API_WHITE_LIST_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 开关未启用跳过当前过滤器
        if (Boolean.FALSE.equals(this.property.getApiWhiteList().getEnabled())) {
            return chain.filter(exchange);
        }

        final long start = System.nanoTime();

        final String path = exchange.getRequest().getPath().value();
        // 1. 默认忽略清单
        if (UrlUtil.isMatchLike(DEFAULT_IGNORED_APIS, path)) {
            markWhited(exchange);
            return checkThenChain(exchange, chain, start);
        }

        // 2. 缓存存在则直接匹配
        return Mono.justOrEmpty(snapshot.get())
            .filter(set -> !set.isEmpty())
            .switchIfEmpty(loadApiWhiteList())
            .flatMap(list -> {
                if (UrlUtil.isMatch(list.stream().toList(), path)) {
                    markWhited(exchange);
                }

                return checkThenChain(exchange, chain, start);
            });
    }

    private void markWhited(ServerWebExchange exchange) {
        ReactorUtil.setAttribute(exchange, ServerWebExchangeContextConstant.WHITED_FLAG, true);
    }

    private Mono<Void> checkThenChain(ServerWebExchange exchange, GatewayFilterChain chain, long start) {
        return chain.filter(exchange)
            .doFinally(signal -> log.info("{} execute cost={} ms", this.getClass().getSimpleName(),
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)));
    }

    private Mono<Set<String>> loadApiWhiteList() {
        return mgtClient.listApi()
            .defaultIfEmpty(List.of())
            .map(this::getStringList)
            .doOnNext(snapshot::set)
            .doOnNext(list -> log.info("API白名单加载完成，条目数={}", list.size()))
            .subscribeOn(Schedulers.boundedElastic());
    }

    private Set<String> getStringList(List<String> list) {
        Set<String> set = new HashSet<>(list);
        List<String> local = property.getApiWhiteList().getIgnoredApi();
        if (CollUtil.isNotEmpty(local)) {
            set.addAll(local);
        }
        return Set.copyOf(set);
    }

    /**
     * 刷新白名单.
     *
     * @param message 消息
     */
    public void refreshWhiteList(MessageBaseDTO<ApiWhiteListChangeDTO> message) {
        if (Objects.isNull(message) || Objects.isNull(message.getOperateType()) || Objects.isNull(message.getData())) {
            return;
        }

        final OperateTypeEnum operateType = BaseEnum.fromValue(message.getOperateType(), OperateTypeEnum.class);
        final ApiWhiteListChangeDTO data = message.getData();
        Set<String> oldSet = snapshot.get();
        Set<String> newSet = new HashSet<>(oldSet);
        switch (operateType) {
            case ADD:
                if (CollUtil.isNotEmpty(data.getNewApiUrl())) {
                    newSet.addAll(data.getNewApiUrl());
                }
                break;
            case DELETE:
                if (CollUtil.isNotEmpty(data.getOldApiUrl())) {
                    newSet.removeAll(data.getOldApiUrl());
                }
                break;
            case MODIFY:
                if (CollUtil.isNotEmpty(data.getOldApiUrl()) && CollUtil.isNotEmpty(data.getNewApiUrl())) {
                    newSet.removeAll(data.getOldApiUrl());
                    newSet.addAll(data.getNewApiUrl());
                }
                break;
            default:
                throw new BizException(BizCodeEnum.UNSUPPORTED_TYPE, new Object[]{message.getOperateType()});
        }
        snapshot.set(Set.copyOf(newSet));
        log.info("API白名单刷新完成，条目数={}", newSet.size());
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        loadApiWhiteList().subscribe();
    }

}
